package com.huawei.hms.framework.network.restclient.hwhttp.dns.dnresolver;

import android.text.TextUtils;
import com.huawei.hms.framework.common.Logger;
import com.huawei.hms.framework.network.restclient.hwhttp.dns.DNManager.ResolveTriggerType;
import com.huawei.hms.framework.network.restclient.hwhttp.dns.DNManager.ResolverSource;
import com.huawei.hms.framework.network.restclient.hwhttp.dns.cache.CacheManager;
import com.huawei.hms.framework.network.restclient.hwhttp.dns.dnresolver.DNResolver.DNResolverCallback;
import com.huawei.hms.framework.network.restclient.hwhttp.dns.dnresolver.dnkeeper.DomainResult;
import com.huawei.hms.framework.network.restclient.hwhttp.dns.dnstask.TaskManager;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class DNResolverManager {
    private static final String TAG = "DNResolverManager";
    private static Set<String> domainSet = Collections.synchronizedSet(new HashSet());
    private static final TaskManager taskManager = TaskManager.getInstance();

    public static class LazyUpdateCallback implements DNResolverCallback {
        public void onRespone(String str, DomainResult domainResult) {
            Logger.v(DNResolverManager.TAG, "lazyUpdateCallback onRespone : " + domainResult);
            CacheManager.saveValidIP(str, domainResult);
            DNResolverManager.domainSet.remove(str);
        }

        public void onFailure(String str, Throwable th) {
            Logger.v(DNResolverManager.TAG, "lazyUpdateCallback onFailure");
            DNResolverManager.domainSet.remove(str);
        }
    }

    public static void dnsLazyUpdate(String str, @ResolveTriggerType String str2) {
        if (!TextUtils.isEmpty(str) && !domainSet.contains(str)) {
            domainSet.add(str);
            Logger.i(TAG, "enter Dns lazy update flow, domain: %s, trigger type: %s", str, str2);
            taskManager.enqueue(new LocalDNSResolver(str, str2, new LazyUpdateCallback()));
        }
    }

    public static DomainResult queryHostSync(DNResolver dNResolver) {
        dNResolver.run();
        return dNResolver.get();
    }

    public static DomainResult queryHostSync(String str, @ResolverSource int i) throws UnknownHostException {
        switch (i) {
            case 4:
                Logger.v(TAG, "queryHostSync domain:" + str + " LocalDNS resolve");
                break;
            case 5:
                return Dns.DNKEEPER.lookup(str);
            case 6:
                return Dns.FILE_CACHE.lookup(str);
        }
        Logger.i(TAG, "Get invalid Dns resolver source:" + str + ", try to use LocalDNS resolve");
        DomainResult lookup = taskManager.lookup(str);
        Logger.v(TAG, "dnsResult: " + lookup);
        return lookup;
    }
}
